package com.lagou.framework.common;

import lombok.Data;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author srh
 * @date 2020/03/31
 **/
@Data
public class Request {
    /**
     * socket中元数据
     */
    private InputStream inputStream;
    /**
     * 解析得到的请求方法
     */
    private String method;
    /**
     * 解析得到的请求url
     */
    private String url;

    public Request(InputStream inputStream) throws IOException {
        this.inputStream = inputStream;

        // 等待数据传输过来
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }
        // 解析成字符串
        byte[] requestBytes = new byte[count];
        inputStream.read(requestBytes);
        String requestStr = new String(requestBytes);
        // 解析method & url
        parseRequestHead(requestStr);
    }

    /**
     * 解析请求头
     *
     * @param requestStr
     */
    private void parseRequestHead(String requestStr) {
        // GET /index.html HTTP/1.1
        String firstLineStr = requestStr.split("\\n")[0];
        String[] keyValue = firstLineStr.split(" ");
        this.method = keyValue[0];
        this.url = keyValue[1];
        System.out.println(String.format("parseRequestHead: method[%s], url[%s]", method, url));
    }
}
